/*
 * @Date: 2021-08-18 09:43:19
 * @information: 日记数据库操作层
 */
import DiaryModel from '../model/DiaryModel'
import UserModel from '../model/UserModel'

// 表关联
DiaryModel.belongsTo(UserModel, {
  foreignKey: 'user_id',
  targetKey: 'id',
  as: 'userInfo',
})


export default class DiaryDao {
  async findAll (data) {
    const { page, size } = data
    return await DiaryModel.findAll({
      attributes: {
        exclude: ['isdelete', 'user_id'], // 返回值排除字段
      },
      include: {
        model: UserModel,
        as: 'userInfo',
        where: {
          isdelete: 0,
        },
        attributes: ['username', 'avatarUrl', 'sex'],
      },
      order: [ // 排序
        ['createtime', 'DESC']
      ],
      where: {
        isdelete: 0,
      },
      offset: (page - 1) * size, // 跳过几个实例
      limit: size, // 获取几个实例
    })
  }

  async findByUserId (data) {
    const { page, size, userId } = data
    return DiaryModel.findAll({
      attributes: {
        exclude: ['isdelete', 'user_id'] // 返回值排除字段
      },
      include: {
        model: UserModel,
        as: 'userInfo',
        where: {
          isdelete: 0,
        },
        attributes: ['username'],
      },
      order: [ // 排序
        ['createtime', 'DESC']
      ],
      where: {
        isdelete: 0,
        userId,
      },
      offset: (page - 1) * size, // 跳过几个实例
      limit: size, // 获取几个实例
    })
  }

  async getCount (userId) {
    const where = {
      isdelete: 0,
    }
    userId && (where.userId = userId)
    return await DiaryModel.count({
      where
    })
  }

  async add (data) {
    return await DiaryModel.create(data)
  }

  async update (data) {
    const { id, content, updatetime } = data
    return await DiaryModel.update({ content, updatetime }, {
      where: {
        isdelete: 0,
        id,
      }
    })
  }

  async del (data) {
    const { id } = data
    return await DiaryModel.update({ isdelete: 1 }, {
      where: {
        isdelete: 0,
        id,
      }
    })
  }




}


